/**
 * 
 */
package com.lorizz.picpub.task.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.lorizz.picpub.query.UpmQueries;
import com.lorizz.picpub.task.TaskSelector;
import com.lorizz.upm.Task;
import com.lorizz.upm.TaskState;
import com.lorizz.upm.repository.Repository;

/**
 * @author wind hong
 * 
 */
public class TaskSelectorImpl implements TaskSelector {

    private Repository upmRepository;
    private int batchSize;

    public void setUpmRepository(Repository upmRepository) {
        this.upmRepository = upmRepository;
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    @Transactional
    @Override
    public List<Long> selectIds() {
        List<Task> tasks = upmRepository.executeQuery(UpmQueries.instance().prioritizedNewTasks(), 0, batchSize);
        List<Long> taskIds = new ArrayList<Long>();
        for (Task task : tasks) {
            task.setState(TaskState.QUEUED);
            taskIds.add(task.getId());
        }
        return taskIds;
    }

    @Transactional
    @Override
    public void returnIds(List<Long> ids) {
        List<Task> tasks = upmRepository.executeQuery(UpmQueries.instance().tasks(ids));
        for (Task task : tasks) {
            task.setState(TaskState.NEW);
        }
    }

}
